<template>
  <div class="login">
    <van-nav-bar title="登录" class="login-title" />
    <!-- 输入框 -->
    <van-cell-group>
      <!-- 表单-验证 -->
      <van-form @submit="onSubmit">
        <van-field v-model="user.mobile" placeholder="请输入手机号" :rules="rules.mobile" >
          <template #left-icon>
            <i class="iconfont icon-iPhone"></i>
          </template>
        </van-field>
        <van-field v-model="user.code" placeholder="请输入验证码" :rules="rules.code" >
          <template #button>
            <!-- native-type="button"避免点击发送验证码时触发表单的submit事件 -->
            <van-button size="small" round native-type="button">发送验证码</van-button>
          </template>
          <template #left-icon>
            <i class="iconfont icon-lock"></i>
          </template>
        </van-field>
        <div class="login-btn">
          <van-button type="info" size="large">登录</van-button>
        </div>
      </van-form>
    </van-cell-group>
  </div>
</template>

<script>
import { getLogin } from '@/api/user.js'
import { localSet } from '@/utils/local.js'

export default {
  data () {
    return {
      user: {
        mobile: '18511111111',
        code: '246810'
      },
      // 验证表单元素规则
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'onBlur' },
          // 正则验证
          { pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '手机号格式不正确', trigger: 'onBlur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'onBlur' },
          { pattern: /\d{6}/, message: '验证码格式不正确', trigger: 'onBlur' }
        ]
      }
    }
  },
  methods: {
    // 点击登录，触发表单的submit事件，在表单验证通过之后才会触发
    async onSubmit () {
      // console.log('submit')
      const res = await getLogin(this.user)
      // console.log('登录', res)
      // 将用户信息保存到vuex中
      this.$store.commit('setUserInfo', res.data)
      // 将用户信息还要存到本地
      localSet('userInfo', res.data)
      // 提示用户
      this.$toast.success('登录成功')
      if (this.$route.path === '/login') {
        // 跳转至首页
        this.$router.push('/home')
      } else {
        this.$router.back()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login {

  .login-title {
    background-color: #3296fa;
  }

  /deep/.van-nav-bar__title {
    color: #fff;
  }

  /deep/ .van-button--default{
    background-color: #ededed;
  }

  .iconfont{
    color: #666;
    font-size: 20px;
  }

  .login-btn{
    margin: 20px;
  }
}
</style>
